package com.ittx.dzt.weidian.service;

import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.ShipmentDispatchDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.log.monitor.ExceptionLog;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.weidian.handler.AbstractBaseWeidianApiHandler;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 拆单发货
 * <p>
 * cy.shipment.orders.dispatch
 * 子单拆单发货(vdian.order.deliver.split.sub)
 * https://open.weidian.com/#/api/211
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/4/1
 */
@Slf4j
@Service
public class WeidianShipmentOrdersDispatchService extends AbstractBaseWeidianApiHandler<ShipmentDispatchDTO> {

	@Override
	public String getWeidianMethod() {
		return "vdian.order.deliver.split.sub";
	}

	@Override
	public String getWeidianApiVersion() {
		return "1.0";
	}

	@Override
	public String getWeidianApiFormat() {
		return null;
	}

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SHIPMENT_ORDERS_DISPATCH;
	}

	@Override
	public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, ShipmentDispatchDTO dto) {
		try {
			Map<String, Object> params = new HashMap<>();
			params.put("order_id", dto.getSourceOrderCode());
			if (dto.getPacks() == null) {
				return Result.error("拆单发货,包裹不可为空");
			}
			if (dto.getPacks().size() > 1) {
				return Result.error("拆单发货,多包裹只能多次调用,每次调用仅允许1个包裹");
			}
			List<Map<String, Object>> splitItemList = new ArrayList<>();
			Optional.ofNullable(dto.getPacks().get(0).getDetails()).ifPresent(tempDetails ->
					tempDetails.forEach(detail -> {
						Map<String, Object> spiltItemMap = new HashMap<>();
						spiltItemMap.put("subOrderId", detail.getSourceLineNum());
						spiltItemMap.put("sku_id", detail.getSourceSkuId());
						spiltItemMap.put("item_id", detail.getSourceSpuId());
						spiltItemMap.put("count", detail.getShipQty());
						spiltItemMap.put("express_type", dto.getCarrierCode());
						spiltItemMap.put("express_custom", dto.getCarrierName());
						spiltItemMap.put("express_no", dto.getWaybillCode());
						splitItemList.add(spiltItemMap);
					}));
			params.put("spilt_item_list", splitItemList);
			return (Result<?>) this.executeWeidianApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
		} catch (Exception e) {
			//访问异常。错误信息，requestId={},平台[{}]接口[{}]执行失败,异常原因：[{}]
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), platformApiParamDTO.getApi(), e.getMessage());
			log.error(msg, e.fillInStackTrace());
			ExceptionLog.error(e, msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg));
		}
	}
}
